# -*- coding: utf-8 -*-
import iis_bridge.pool as pool
import iis_bridge.site as site
import os
import subprocess
import shutil;
from xml.etree.ElementTree import ElementTree, Element

rootpath = "D:\\wwwroot\\";  # 所有站点的目录


# icacls e:\tt\a\* /grant "iis apppool\mysite.com:R"
# icacls e:\tt\a\1.txt /grant "iis apppool\mysite.com:M"
def set_icacls(domainname):
    sitepath = rootpath + domainname + "\\public_html"
    cmd = [];
    cmd_d = ["App_Data", "db", "upload", "news\\uppic", "news\\attached", "news\\admin\\uppicimg", "products\\UpLoadFile"];  # 需要给出写权限的目录
    cmd1 = "icacls " + sitepath + " /grant \"iis apppool\\" + domainname + ":(R)\" /T"
    cmd.append(cmd1);

    for i1 in cmd_d:
        cmd21 = "icacls " + sitepath + "\\" + i1 + " /grant \"iis apppool\\" + domainname + ":M\" /T";
        # print cmd21;
        cmd.append(cmd21);

    for i2 in cmd:
        proc = subprocess.Popen(i2, shell=True, stdout=subprocess.PIPE)
        proc.communicate();


# cacls e:\tt\a  /e /t /g  "iis apppool\djsocks.com":C  #写/修改
# cacls e:\tt\a  /e /t /g  "iis apppool\djsocks.com":R  #读
# 采用cacls,简单，另外不会有问题
def set_cacls(domainname):
    sitepath = rootpath + domainname + "\\public_html"
    cmd = []
    cmd_d = ["App_Data", "db", "upload", "news\\uppic", "news\\attached", "news\\admin\\uppicimg", "products\\UpLoadFile"];  # 需要给出写权限的目录
    cmd1 = "cacls " + sitepath + " /e /t /g  \"iis apppool\\" + domainname + "\":R "
    cmd.append(cmd1)

    for i1 in cmd_d:
        cmd21 = "cacls " + sitepath + "\\" + i1 + " /e /t /g  \"iis apppool\\" + domainname + "\":C ";
        # print cmd21;
        cmd.append(cmd21)

    for i2 in cmd:
        proc = subprocess.Popen(i2, shell=True, stdout=subprocess.PIPE)
        proc.communicate()


def add_newsite(domainname):
    sitepath = rootpath + domainname + "\\public_html"    
    pool.create(domainname)
    pool.config(domainname, runtime_version="2.0",identity="ApplicationPoolIdentity");
    site.create(domainname, 80, sitepath, domainname, "http", None, 'www.' + domainname, '');
    site.add_binding(domainname, "http", 80, domainname, "");

	
def set_pools(sitelist):
    for i in sitelist:
        i = i.replace("\n", "");
        print i;        
        pool.config(i, runtime_version="2.0",identity="ApplicationPoolIdentity");
        
	
	
# 去掉web.config中的system.webserver，防止配置冲突。实际未使用
def p_xml():
    xmlpath = sitepath + "\\web.config";
    tree = ElementTree()
    root = tree.parse(xmlpath)
    webserver = root.find("system.webServer");
    root.remove(webserver);
    tree.write(xmlpath, "utf-8", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>")


# 加载待添加站点列表
def get_sitelist():
    fp = open(rootpath + "list.txt");  # 列表文件路径
    a = fp.readlines();
    return a;

	
	# 加载待添加站点列表
def get_del_sitelist():
    fp = open(rootpath + "del_list.txt");  # 列表文件路径
    a = fp.readlines();
    return a;

	
def add_sites(sitelist):
    for i in sitelist:
        i = i.replace("\n", "");
        print i;
        if site.exists(i):
            print i + " exists";
            continue;
        add_newsite(i);
        set_cacls(i);
		

# 批量恢复站点
def recover_sites():
    sitelist = get_sitelist();
    add_sites(sitelist);


# 全新添加站点时用，自动建目录。但是权限要在文件传好后，再运行脚本设置
def add_new_site1(domain):
    #domain = "ff3.com"
	# 建立目录结构
    new_site_dir(domain)
    # 新建iis站点
    add_newsite(domain)    
    # 设置权限(写权限的目录需要重新手工调用)
    set_cacls(domain)

	
# 增加一批特殊的站点（共用同一应用池）
def add_test_site(sitelist):
	for i in sitelist:
		i = i.replace("\n", "");
		print i
		domainname = i + ".35.net"
		sitepath = rootpath + i		
		site.create(domainname, 80, sitepath, "aspx2", "http", None, domainname, '');
		#site.add_binding(domainname, "http", 80, domainname, "");
	
	
def remove_sites(sitelist):
	for i in sitelist:
		i = i.strip()
		i = i.replace("\n", "")
		print "removeing site: " + i		
		if site.exists(i):
			site.delete(i)
		if pool.exists(i):
			pool.delete(i)
		try:
			shutil.move(rootpath + i,"E:\\del_sites\\" + i)
		except WindowsError:
			print "del error: " + i;
			continue;
	print "Finish";

	
# 根据域名建立标准网站结构
def new_site_dir(domain):
    domain = domain.replace("www.", "")
    try:
        os.makedirs(rootpath+domain+"\\logs")
        os.makedirs(rootpath+domain+"\\public_html")
        print "目录建立完毕"
    except WindowsError:
        print "目录已经存在或没写权限";
	
		
if __name__ == '__main__':
	#sitelist = get_del_sitelist();
	#remove_sites(sitelist);	
	#add_test_site(sitelist);
    #set_pools(sitelist);	
    #add_sites(sitelist);
    add_new_site1("ff3.com")
